package com.hyd.pachosting;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
public class DatabaseInitializer implements CommandLineRunner {

    private static final String[] TABLES = {
        "t_user", "t_proxy", "t_pattern"
    };

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否存在 user 表
        String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME in "
            + "('" + String.join("','", TABLES) + "')";
        Integer tableCount = jdbcTemplate.queryForObject(sql, Integer.class);

        if (tableCount == null || tableCount < TABLES.length) {
            log.info("There are missing tables. Initializing database...");
            // 执行 schema.sql 中的初始化脚本
            jdbcTemplate.execute("RUNSCRIPT FROM 'classpath:schema.sql'");
            log.info("Database initialization completed successfully.");
        } else {
            log.info("Tables already exist. No initialization required.");
        }
    }
}
